<!-- Stripe脚本加载 -->
<script src="https://js.stripe.com/v3/"></script>

<!-- 支付配置检查 -->
<div class="row mb-4">
    <div class="col-12">
        <div class="card feature-card">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <h5 class="card-title mb-1">
                            <i class="fas fa-cog text-info me-2"></i>
                            Stripe配置状态
                        </h5>
                        <p class="text-muted mb-0">检查Stripe支付配置和连接状态</p>
                    </div>
                    <div>
                        <span id="stripe-status" class="status-badge status-stopped">
                            <i class="fas fa-circle me-1"></i>检查中
                        </span>
                    </div>
                </div>
                
                <div id="stripe-config" class="mt-3"></div>
                
                <div class="text-center mt-3">
                    <button class="btn btn-outline-primary btn-custom" onclick="checkStripeConfig()">
                        <i class="fas fa-refresh me-1"></i>重新检查配置
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 支付意图测试 -->
<div class="row mb-4">
    <div class="col-md-6 mb-3">
        <div class="card feature-card h-100">
            <div class="card-body">
                <h5 class="card-title">
                    <i class="fas fa-credit-card text-primary me-2"></i>
                    创建支付意图
                </h5>
                <p class="text-muted">测试创建Stripe支付意图</p>
                
                <div class="mb-3">
                    <label class="form-label">支付金额 (分)</label>
                    <input type="number" class="form-control" id="payment-amount" value="2000" min="50">
                    <small class="text-muted">最小金额: 50分 (0.5元)</small>
                </div>
                
                <div class="mb-3">
                    <label class="form-label">货币类型</label>
                    <select class="form-select" id="payment-currency">
                        <option value="cny">CNY (人民币)</option>
                        <option value="usd">USD (美元)</option>
                        <option value="eur">EUR (欧元)</option>
                    </select>
                </div>
                
                <div class="mb-3">
                    <label class="form-label">认证Token</label>
                    <input type="text" class="form-control" id="payment-auth-token" placeholder="Bearer token...">
                    <small class="text-muted">需要登录用户才能创建支付</small>
                </div>
                
                <button class="btn btn-primary w-100 btn-custom" onclick="createPaymentIntent()">
                    <i class="fas fa-plus me-1"></i>创建支付意图
                </button>
            </div>
        </div>
    </div>
    
    <div class="col-md-6 mb-3">
        <div class="card feature-card h-100">
            <div class="card-body">
                <h5 class="card-title">
                    <i class="fas fa-search text-success me-2"></i>
                    查询支付状态
                </h5>
                <p class="text-muted">查询支付意图的当前状态</p>
                
                <div class="mb-3">
                    <label class="form-label">支付意图ID</label>
                    <input type="text" class="form-control" id="payment-intent-id" placeholder="pi_xxxxxx">
                    <small class="text-muted">从创建支付响应中获取</small>
                </div>
                
                <div class="mb-3">
                    <button class="btn btn-success w-100 btn-custom" onclick="getPaymentIntent()">
                        <i class="fas fa-search me-1"></i>查询支付状态
                    </button>
                </div>
                
                <div class="mb-3">
                    <button class="btn btn-warning w-100 btn-custom" onclick="confirmPaymentIntent()">
                        <i class="fas fa-check me-1"></i>确认支付
                    </button>
                </div>
                
                <div class="mb-3">
                    <button class="btn btn-danger w-100 btn-custom" onclick="cancelPaymentIntent()">
                        <i class="fas fa-times me-1"></i>取消支付
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 订阅测试 -->
<div class="row mb-4">
    <div class="col-12">
        <div class="card feature-card">
            <div class="card-body">
                <h5 class="card-title">
                    <i class="fas fa-sync text-warning me-2"></i>
                    订阅管理测试
                </h5>
                <p class="text-muted">测试订阅的创建、取消和查询功能</p>
                
                <div class="row">
                    <div class="col-md-4">
                        <div class="mb-3">
                            <label class="form-label">价格ID</label>
                            <input type="text" class="form-control" id="subscription-price-id" placeholder="price_xxxxxx">
                            <small class="text-muted">Stripe价格ID</small>
                        </div>
                        <button class="btn btn-warning w-100 btn-custom" onclick="createSubscription()">
                            <i class="fas fa-plus me-1"></i>创建订阅
                        </button>
                    </div>
                    <div class="col-md-4">
                        <div class="mb-3">
                            <label class="form-label">订阅ID</label>
                            <input type="text" class="form-control" id="subscription-id" placeholder="sub_xxxxxx">
                            <small class="text-muted">从创建响应中获取</small>
                        </div>
                        <button class="btn btn-info w-100 btn-custom" onclick="getSubscription()">
                            <i class="fas fa-search me-1"></i>查询订阅
                        </button>
                    </div>
                    <div class="col-md-4">
                        <div class="mb-3">
                            <label class="form-label">&nbsp;</label>
                            <div></div>
                        </div>
                        <button class="btn btn-danger w-100 btn-custom" onclick="cancelSubscription()">
                            <i class="fas fa-times me-1"></i>取消订阅
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 支付历史 -->
<div class="row mb-4">
    <div class="col-12">
        <div class="card feature-card">
            <div class="card-body">
                <h5 class="card-title">
                    <i class="fas fa-history text-info me-2"></i>
                    支付历史查询
                </h5>
                <p class="text-muted">查询用户的支付历史记录</p>
                
                <div class="row">
                    <div class="col-md-8">
                        <div class="mb-3">
                            <label class="form-label">查询参数 <small class="text-muted">(可选)</small></label>
                            <div class="row">
                                <div class="col-md-4">
                                    <input type="number" class="form-control" id="history-limit" placeholder="限制数量" min="1" max="100">
                                </div>
                                <div class="col-md-4">
                                    <select class="form-select" id="history-status">
                                        <option value="">所有状态</option>
                                        <option value="succeeded">成功</option>
                                        <option value="pending">待处理</option>
                                        <option value="failed">失败</option>
                                    </select>
                                </div>
                                <div class="col-md-4">
                                    <input type="date" class="form-control" id="history-date" placeholder="日期">
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="mb-3">
                            <label class="form-label">&nbsp;</label>
                            <button class="btn btn-info w-100 btn-custom" onclick="getPaymentHistory()">
                                <i class="fas fa-list me-1"></i>查询历史
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Webhook测试 -->
<div class="row mb-4">
    <div class="col-12">
        <div class="card feature-card">
            <div class="card-body">
                <h5 class="card-title">
                    <i class="fas fa-webhook text-dark me-2"></i>
                    Webhook测试
                </h5>
                <p class="text-muted">测试Stripe Webhook处理功能</p>
                
                <div class="alert alert-info">
                    <i class="fas fa-info-circle me-1"></i>
                    <strong>注意:</strong> Webhook端点为 <code>/api/v1/payments/webhook</code>，需要在Stripe控制台中配置。
                    本地测试可以使用Stripe CLI进行。
                </div>
                
                <div class="code-block">
# 使用Stripe CLI测试Webhook
stripe listen --forward-to localhost:3379/api/v1/payments/webhook

# 触发测试事件
stripe trigger payment_intent.succeeded
stripe trigger customer.subscription.created
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 测试结果显示 -->
<div class="row">
    <div class="col-12">
        <div class="card feature-card">
            <div class="card-body">
                <h5 class="card-title">
                    <i class="fas fa-terminal text-dark me-2"></i>
                    测试结果
                </h5>
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <div></div>
                    <button class="btn btn-outline-secondary btn-sm" onclick="clearPaymentResults()">
                        <i class="fas fa-eraser me-1"></i>清空结果
                    </button>
                </div>
                <div id="payment-results" class="code-block">
                    等待测试结果...
                </div>
            </div>
        </div>
    </div>
</div>

<script>
// 全局变量
let stripe = null;
let stripeConfig = null;

// 页面加载时初始化
document.addEventListener('DOMContentLoaded', function() {
    showPaymentResult('🚀 支付测试页面已加载');
    
    // 从localStorage加载token
    const savedToken = localStorage.getItem('access_token');
    if (savedToken) {
        document.getElementById('payment-auth-token').value = savedToken;
    }
    
    // 检查Stripe配置
    checkStripeConfig();
});

// 检查Stripe配置
async function checkStripeConfig() {
    try {
        showPaymentResult('🔍 检查Stripe配置...');
        
        const response = await fetch('/api/v1/payments/config');
        const data = await response.json();
        
        const statusEl = document.getElementById('stripe-status');
        const configEl = document.getElementById('stripe-config');
        
        if (data.success) {
            stripeConfig = data.data;
            statusEl.className = 'status-badge status-running';
            statusEl.innerHTML = '<i class="fas fa-circle me-1"></i>配置正常';
            
            configEl.innerHTML = `
                <div class="row">
                    <div class="col-md-6">
                        <p class="mb-1"><strong>可发布密钥:</strong> ${stripeConfig.publishableKey ? '✅ 已配置' : '❌ 未配置'}</p>
                        <p class="mb-1"><strong>Webhook端点:</strong> ${stripeConfig.webhookEndpoint}</p>
                        <p class="mb-0"><strong>支持货币:</strong> ${stripeConfig.currencies.join(', ')}</p>
                    </div>
                    <div class="col-md-6">
                        <p class="mb-1"><strong>环境:</strong> ${stripeConfig.mode}</p>
                        <p class="mb-1"><strong>国家:</strong> ${stripeConfig.country}</p>
                        <p class="mb-0"><strong>最小金额:</strong> ${stripeConfig.minAmount} 分</p>
                    </div>
                </div>
            `;
            
            // 初始化Stripe
            if (stripeConfig.publishableKey && typeof Stripe !== 'undefined') {
                stripe = Stripe(stripeConfig.publishableKey);
                showPaymentResult('✅ Stripe配置加载成功');
            } else {
                showPaymentResult('⚠️ Stripe公钥未配置或Stripe.js未加载');
            }
        } else {
            statusEl.className = 'status-badge status-stopped';
            statusEl.innerHTML = '<i class="fas fa-circle me-1"></i>配置错误';
            configEl.innerHTML = `<div class="alert alert-danger">❌ ${data.message}</div>`;
            showPaymentResult('❌ Stripe配置检查失败: ' + data.message);
        }
    } catch (error) {
        showPaymentResult('💥 检查Stripe配置出错: ' + error.message);
        const statusEl = document.getElementById('stripe-status');
        statusEl.className = 'status-badge status-stopped';
        statusEl.innerHTML = '<i class="fas fa-circle me-1"></i>连接失败';
    }
}

// 创建支付意图
async function createPaymentIntent() {
    const amount = document.getElementById('payment-amount').value;
    const currency = document.getElementById('payment-currency').value;
    const authToken = document.getElementById('payment-auth-token').value;
    
    if (!amount || amount < 50) {
        showPaymentResult('❌ 请输入有效的支付金额 (最小50分)');
        return;
    }
    
    if (!authToken) {
        showPaymentResult('❌ 请输入认证Token');
        return;
    }
    
    try {
        showPaymentResult('🔄 创建支付意图...');
        
        const response = await fetch('/api/v1/payments/payment-intents', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': authToken.startsWith('Bearer ') ? authToken : `Bearer ${authToken}`
            },
            body: JSON.stringify({
                amount: parseInt(amount),
                currency: currency,
                description: '测试支付意图'
            })
        });
        
        const data = await response.json();
        
        if (data.success) {
            const paymentIntent = data.data.paymentIntent;
            document.getElementById('payment-intent-id').value = paymentIntent.id;
            
            showPaymentResult(`✅ 支付意图创建成功!
ID: ${paymentIntent.id}
金额: ${paymentIntent.amount} ${paymentIntent.currency.toUpperCase()}
状态: ${paymentIntent.status}
客户端密钥: ${paymentIntent.client_secret ? '已生成' : '未生成'}`);
        } else {
            showPaymentResult(`❌ 创建支付意图失败: ${data.message}`);
        }
    } catch (error) {
        showPaymentResult(`💥 创建支付意图出错: ${error.message}`);
    }
}

// 查询支付意图
async function getPaymentIntent() {
    const paymentIntentId = document.getElementById('payment-intent-id').value;
    const authToken = document.getElementById('payment-auth-token').value;
    
    if (!paymentIntentId) {
        showPaymentResult('❌ 请输入支付意图ID');
        return;
    }
    
    if (!authToken) {
        showPaymentResult('❌ 请输入认证Token');
        return;
    }
    
    try {
        showPaymentResult('🔍 查询支付意图...');
        
        const response = await fetch(`/api/v1/payments/payment-intents/${paymentIntentId}`, {
            headers: {
                'Authorization': authToken.startsWith('Bearer ') ? authToken : `Bearer ${authToken}`
            }
        });
        
        const data = await response.json();
        
        if (data.success) {
            const paymentIntent = data.data.paymentIntent;
            showPaymentResult(`✅ 支付意图查询成功!
ID: ${paymentIntent.id}
金额: ${paymentIntent.amount} ${paymentIntent.currency.toUpperCase()}
状态: ${paymentIntent.status}
创建时间: ${new Date(paymentIntent.created * 1000).toLocaleString()}
${paymentIntent.description ? '描述: ' + paymentIntent.description : ''}`);
        } else {
            showPaymentResult(`❌ 查询支付意图失败: ${data.message}`);
        }
    } catch (error) {
        showPaymentResult(`💥 查询支付意图出错: ${error.message}`);
    }
}

// 确认支付意图
async function confirmPaymentIntent() {
    const paymentIntentId = document.getElementById('payment-intent-id').value;
    const authToken = document.getElementById('payment-auth-token').value;
    
    if (!paymentIntentId) {
        showPaymentResult('❌ 请输入支付意图ID');
        return;
    }
    
    if (!authToken) {
        showPaymentResult('❌ 请输入认证Token');
        return;
    }
    
    try {
        showPaymentResult('🔄 确认支付意图...');
        
        const response = await fetch(`/api/v1/payments/payment-intents/${paymentIntentId}/confirm`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': authToken.startsWith('Bearer ') ? authToken : `Bearer ${authToken}`
            }
        });
        
        const data = await response.json();
        
        if (data.success) {
            const paymentIntent = data.data.paymentIntent;
            showPaymentResult(`✅ 支付意图确认成功!
ID: ${paymentIntent.id}
状态: ${paymentIntent.status}
${paymentIntent.status === 'succeeded' ? '🎉 支付已完成!' : '⏳ 支付处理中...'}`);
        } else {
            showPaymentResult(`❌ 确认支付意图失败: ${data.message}`);
        }
    } catch (error) {
        showPaymentResult(`💥 确认支付意图出错: ${error.message}`);
    }
}

// 取消支付意图
async function cancelPaymentIntent() {
    const paymentIntentId = document.getElementById('payment-intent-id').value;
    const authToken = document.getElementById('payment-auth-token').value;
    
    if (!paymentIntentId) {
        showPaymentResult('❌ 请输入支付意图ID');
        return;
    }
    
    if (!authToken) {
        showPaymentResult('❌ 请输入认证Token');
        return;
    }
    
    try {
        showPaymentResult('🔄 取消支付意图...');
        
        const response = await fetch(`/api/v1/payments/payment-intents/${paymentIntentId}/cancel`, {
            method: 'POST',
            headers: {
                'Authorization': authToken.startsWith('Bearer ') ? authToken : `Bearer ${authToken}`
            }
        });
        
        const data = await response.json();
        
        if (data.success) {
            const paymentIntent = data.data.paymentIntent;
            showPaymentResult(`✅ 支付意图取消成功!
ID: ${paymentIntent.id}
状态: ${paymentIntent.status}`);
        } else {
            showPaymentResult(`❌ 取消支付意图失败: ${data.message}`);
        }
    } catch (error) {
        showPaymentResult(`💥 取消支付意图出错: ${error.message}`);
    }
}

// 创建订阅
async function createSubscription() {
    const priceId = document.getElementById('subscription-price-id').value;
    const authToken = document.getElementById('payment-auth-token').value;
    
    if (!priceId) {
        showPaymentResult('❌ 请输入价格ID');
        return;
    }
    
    if (!authToken) {
        showPaymentResult('❌ 请输入认证Token');
        return;
    }
    
    try {
        showPaymentResult('🔄 创建订阅...');
        
        const response = await fetch('/api/v1/payments/subscriptions', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': authToken.startsWith('Bearer ') ? authToken : `Bearer ${authToken}`
            },
            body: JSON.stringify({
                priceId: priceId
            })
        });
        
        const data = await response.json();
        
        if (data.success) {
            const subscription = data.data.subscription;
            document.getElementById('subscription-id').value = subscription.id;
            
            showPaymentResult(`✅ 订阅创建成功!
ID: ${subscription.id}
状态: ${subscription.status}
价格ID: ${subscription.items.data[0].price.id}
客户ID: ${subscription.customer}`);
        } else {
            showPaymentResult(`❌ 创建订阅失败: ${data.message}`);
        }
    } catch (error) {
        showPaymentResult(`💥 创建订阅出错: ${error.message}`);
    }
}

// 查询订阅
async function getSubscription() {
    const subscriptionId = document.getElementById('subscription-id').value;
    const authToken = document.getElementById('payment-auth-token').value;
    
    if (!subscriptionId) {
        showPaymentResult('❌ 请输入订阅ID');
        return;
    }
    
    if (!authToken) {
        showPaymentResult('❌ 请输入认证Token');
        return;
    }
    
    try {
        showPaymentResult('🔍 查询订阅...');
        
        const response = await fetch(`/api/v1/payments/subscriptions/${subscriptionId}`, {
            headers: {
                'Authorization': authToken.startsWith('Bearer ') ? authToken : `Bearer ${authToken}`
            }
        });
        
        const data = await response.json();
        
        if (data.success) {
            const subscription = data.data.subscription;
            showPaymentResult(`✅ 订阅查询成功!
ID: ${subscription.id}
状态: ${subscription.status}
当前周期开始: ${new Date(subscription.current_period_start * 1000).toLocaleDateString()}
当前周期结束: ${new Date(subscription.current_period_end * 1000).toLocaleDateString()}
客户ID: ${subscription.customer}`);
        } else {
            showPaymentResult(`❌ 查询订阅失败: ${data.message}`);
        }
    } catch (error) {
        showPaymentResult(`💥 查询订阅出错: ${error.message}`);
    }
}

// 取消订阅
async function cancelSubscription() {
    const subscriptionId = document.getElementById('subscription-id').value;
    const authToken = document.getElementById('payment-auth-token').value;
    
    if (!subscriptionId) {
        showPaymentResult('❌ 请输入订阅ID');
        return;
    }
    
    if (!authToken) {
        showPaymentResult('❌ 请输入认证Token');
        return;
    }
    
    try {
        showPaymentResult('🔄 取消订阅...');
        
        const response = await fetch(`/api/v1/payments/subscriptions/${subscriptionId}/cancel`, {
            method: 'DELETE',
            headers: {
                'Authorization': authToken.startsWith('Bearer ') ? authToken : `Bearer ${authToken}`
            }
        });
        
        const data = await response.json();
        
        if (data.success) {
            const subscription = data.data.subscription;
            showPaymentResult(`✅ 订阅取消成功!
ID: ${subscription.id}
状态: ${subscription.status}
取消时间: ${subscription.canceled_at ? new Date(subscription.canceled_at * 1000).toLocaleString() : '立即'}
周期结束时间: ${new Date(subscription.current_period_end * 1000).toLocaleString()}`);
        } else {
            showPaymentResult(`❌ 取消订阅失败: ${data.message}`);
        }
    } catch (error) {
        showPaymentResult(`💥 取消订阅出错: ${error.message}`);
    }
}

// 查询支付历史
async function getPaymentHistory() {
    const authToken = document.getElementById('payment-auth-token').value;
    const limit = document.getElementById('history-limit').value;
    const status = document.getElementById('history-status').value;
    const date = document.getElementById('history-date').value;
    
    if (!authToken) {
        showPaymentResult('❌ 请输入认证Token');
        return;
    }
    
    try {
        showPaymentResult('🔍 查询支付历史...');
        
        // 构建查询参数
        const params = new URLSearchParams();
        if (limit) params.append('limit', limit);
        if (status) params.append('status', status);
        if (date) params.append('date', date);
        
        const url = `/api/v1/payments/history${params.toString() ? '?' + params.toString() : ''}`;
        
        const response = await fetch(url, {
            headers: {
                'Authorization': authToken.startsWith('Bearer ') ? authToken : `Bearer ${authToken}`
            }
        });
        
        const data = await response.json();
        
        if (data.success) {
            const payments = data.data.payments;
            let result = `✅ 支付历史查询成功! (共 ${payments.length} 条记录)\n\n`;
            
            payments.forEach((payment, index) => {
                result += `${index + 1}. ID: ${payment.id}
   金额: ${payment.amount} ${payment.currency.toUpperCase()}
   状态: ${payment.status}
   时间: ${new Date(payment.created * 1000).toLocaleString()}
   ${payment.description ? '描述: ' + payment.description : ''}\n\n`;
            });
            
            showPaymentResult(result);
        } else {
            showPaymentResult(`❌ 查询支付历史失败: ${data.message}`);
        }
    } catch (error) {
        showPaymentResult(`💥 查询支付历史出错: ${error.message}`);
    }
}

// 显示支付测试结果
function showPaymentResult(message) {
    const resultEl = document.getElementById('payment-results');
    const timestamp = new Date().toLocaleTimeString();
    resultEl.innerHTML += `[${timestamp}] ${message}\n`;
    resultEl.scrollTop = resultEl.scrollHeight;
}

// 清空支付测试结果
function clearPaymentResults() {
    document.getElementById('payment-results').textContent = '等待测试结果...';
}
</script> 